#include "DataPCH.h"
#include "DataConfigs.h"

#include "RapidXML/rapidxml.hpp"
#include "Pf/PfFileIO.h"

namespace data
{
	char* ReadFile(const std::string& strFilename)
	{
		pf::FileIO::FileHandle hFile = pf::FileIO::FileOpen(strFilename, pf::FileIO::EFileMode_Read);

		if (hFile != pf::FileIO::cInvalidFileHandle)
		{
			size_t fileSize = pf::FileIO::FileGetSize(hFile);
			char* buf = new char[fileSize];
			memset(buf, 0, fileSize);
			pf::FileIO::FileRead(hFile, buf, fileSize);
			while (pf::FileIO::FileBusy(hFile));
			pf::FileIO::FileClose(hFile);

			size_t cur = fileSize-1;
			while (buf[cur] == 10 || buf[cur] == 13)
				buf[cur--] = 0;

			return buf;
		}

		return 0;
	}

	void DataConfigs_LoadMemorySlotConfigsFromFile(const std::string& strFilename, std::vector<MemorySlotConfig>& outConfigs)
	{
		char* pData = ReadFile(strFilename);

		rapidxml::xml_document<> doc;
		doc.parse<0>(pData);

		rapidxml::xml_node<> *rootNode = doc.first_node("MemorySlotConfigs");

		if (rootNode)
		{
			rapidxml::xml_node<> *slotNode = rootNode->first_node("Slot");
			while (slotNode)
			{
				MemorySlotConfig newConfig;
				int count = 1;

				rapidxml::xml_attribute<>* attr = slotNode->first_attribute();
				while (attr)
				{
					if (_stricmp(attr->name(),"name") == 0)
						newConfig.strType = attr->value();
					if (_stricmp(attr->name(),"size") == 0)
						newConfig.sizeInBytes = atoi(attr->value());
					if (_stricmp(attr->name(),"count") == 0)
						count = atoi(attr->value());
					attr = attr->next_attribute();	
				}

				for (int i = 0; i < count; ++i)
					outConfigs.push_back(newConfig);

				slotNode = slotNode->next_sibling("Slot");
			}
		}

		delete[] pData;
	}

	void DataConfigs_LoadDataBlockConfigsFromFile(const std::string& strFilename, std::vector<DataBlockConfig>& outConfigs)
	{
		char* pData = ReadFile(strFilename);

		rapidxml::xml_document<> doc;
		doc.parse<0>(pData);

		rapidxml::xml_node<> *rootNode = doc.first_node("DataBlockConfigs");

		if (rootNode)
		{
			rapidxml::xml_node<> *dataBlockNode = rootNode->first_node("DataBlock");
			while (dataBlockNode)
			{
				outConfigs.push_back(DataBlockConfig());
				DataBlockConfig& newConfig = outConfigs.back();

				rapidxml::xml_attribute<>* attr = dataBlockNode->first_attribute();
				while (attr)
				{
					if (_stricmp(attr->name(),"name") == 0)
						newConfig.hsName = cr::HashedString(attr->value());
					if (_stricmp(attr->name(),"slottype") == 0)
						newConfig.strSlotType = attr->value();
					if (_stricmp(attr->name(),"filename") == 0)
					{
						newConfig.strFilename = attr->value();
						newConfig.fileSizeInBytes = pf::FileIO::FileGetSize(newConfig.strFilename);
					}
					attr = attr->next_attribute();	
				}

				dataBlockNode = dataBlockNode->next_sibling("DataBlock");
			}
		}

		delete[] pData;
	}
}